import {
  AlipayCircleOutlined,
  LockOutlined,
  MobileOutlined,
  PhoneOutlined,
  UserOutlined,
  SafetyCertificateOutlined,
} from "@ant-design/icons";
import { Alert, message, Modal, Tabs, Button, Checkbox } from "antd";
import React, { useRef, useState } from "react";
import {
  ProFormCaptcha,
  ProFormCheckbox,
  ProFormText,
  LoginForm,
  ProForm
} from "@ant-design/pro-form";
import { useIntl, history, FormattedMessage, SelectLang, useModel } from "umi";
import { getFakeCaptcha } from "@/services/ant-design-pro/login";
import styles from "./index.less";
import { postFetch } from "@/utils/doFetch";
import moment from "moment";
import Tiaokuan from './tiaokuan';


const LoginMessage = ({ content }) => (
  <Alert
    style={{
      marginBottom: 24,
    }}
    message={content}
    type="error"
    showIcon
  />
);

const Login = () => {
  const [type, setType] = useState("account");
  const { initialState, setInitialState } = useModel("@@initialState");
  const intl = useIntl();
  const formRef = useRef(), formRefs = useRef();
  const [modal, setmodal] = useState({
    visible: false,
  });
  const [accept, setaccept] = useState(false);

  const handleSubmit = async (values) => {
    try {
      // 登录
      if (type == "account") {
        const msg = await postFetch({
          url: "/api/user_token",
          params: {
            password: values.password,
            phone: values.phone
          }
        });
        if (msg.code === 0) {
          localStorage.setItem("TOKEN", msg?.data?.token);
          localStorage.setItem("NAME", values.phone);
          const defaultLoginSuccessMessage = intl.formatMessage({
            id: "pages.login.success",
            defaultMessage: "登录成功！",
          });
          message.success(defaultLoginSuccessMessage);
          await setInitialState((s) => ({
            ...s, currentUser: {
              name: values.phone
            }
          }));
          /** 此方法会跳转到 redirect 参数所在的位置 */

          if (!history) return;
          const { query } = history.location;
          const { redirect } = query;
          history.push(redirect || "/");
          return;
        } else {
        }
      } else if (type == "mobile") {
        const msg = await postFetch({
          url: "/api/user/register",
          params: {
            ...values
          }
        });
        if (msg.code === 0) {
          message.success("注册成功！");
          setType("account");
        }

      }

    } catch (error) {
    }
  };


  const compareToFirstPassword = (rule, value, callback) => {

    if (value && value !== formRef.current.getFieldValue('password')) {
      callback('两次密码不一致!');
    } else {
      callback();
    }
  };



  return (
    <div className={styles.container} style={{ backgroundImage: `url(${require("@/assets/loginbg.jpg")})` }}>
      <div className={styles.content} id="content">
        <div className={styles.header}>
          <img src={require("@/assets/logo.png")} alt="" />
          <span>
            批量报告生成器
          </span>
          <img src={require("@/assets/logo_ed.png")} alt="" />

        </div>

        <div className={styles.right}>
          <LoginForm
            initialValues={{
              phone: "",
              password: ""
            }}
            onFinish={async (values) => {
              await handleSubmit(values);
            }}
            submitter={{
              searchConfig: {
                resetText: "",
                submitText: type === "account" ? "登录" : "注册",
              },
              submitButtonProps: {
                disabled: type == "mobile" && !accept ? true : false,
                size: "large",
                style: { width: "100%" }
              }
            }}

            formRef={formRef}
          >
            <Tabs activeKey={type} onChange={setType} animated>
              <Tabs.TabPane
                key="account"
                tab={"登录"}
              >
              </Tabs.TabPane>

              <Tabs.TabPane
                key="mobile"
                tab={"注册"}
              >
              </Tabs.TabPane>
            </Tabs>
            {
              type === "account" && (
                <>
                  <ProFormText
                    name="phone"
                    fieldProps={{
                      size: "large",
                      prefix: <PhoneOutlined rotate={90} className={styles.prefixIcon} />,
                    }}
                    placeholder={"用户名"}
                    rules={[
                      {
                        required: true,
                        message: (
                          "请输入用户名!"
                        ),
                      },
                    ]}
                  />
                  <ProFormText.Password
                    name="password"
                    fieldProps={{
                      size: "large",
                      prefix: <LockOutlined className={styles.prefixIcon} />,
                    }}
                    placeholder={"密码"}
                    rules={[
                      {
                        required: true,
                        message: ("请输入密码"),
                      },
                    ]}
                  />
                  <div
                    style={{
                      marginBottom: 24,
                    }}
                  >
                    <ProFormCheckbox noStyle name="autoLogin">
                      记住密码
                    </ProFormCheckbox>
                    <a
                      style={{
                        float: "right",
                      }}
                      onClick={() => {
                        setmodal(s => ({
                          ...s,
                          visible: true
                        }))
                      }}
                    >
                      忘记密码
                    </a>
                  </div>
                </>
              )
            }
            {
              type === "mobile" && (
                <>
                  <ProFormText
                    fieldProps={{
                      size: "large",
                      prefix: <MobileOutlined className={styles.prefixIcon} />,
                    }}
                    name="phone"
                    placeholder={"手机号"}
                    rules={[
                      {
                        required: true,
                        message: "请输入手机号！",
                      },
                      {
                        pattern: /^1\d{10}$/,
                        message: "手机号格式错误！",
                      },
                    ]}
                  />

                  <ProFormText.Password
                    name="password"
                    fieldProps={{
                      size: "large",
                      prefix: <LockOutlined className={styles.prefixIcon} />,
                    }}
                    placeholder={"密码"}
                    rules={[
                      {
                        required: true,
                        message: ("请输入密码"),
                      }
                    ]}
                  />

                  <ProFormText.Password
                    name="confirm"
                    fieldProps={{
                      size: "large",
                      prefix: <LockOutlined className={styles.prefixIcon} />,
                    }}
                    placeholder={"确认密码"}
                    rules={[
                      {
                        required: true,
                        message: ("请输入密码"),
                      },
                      {
                        validator: compareToFirstPassword
                      }
                    ]}
                  />


                  <ProFormCaptcha
                    fieldProps={{
                      size: "large",
                      prefix: <SafetyCertificateOutlined className={styles.prefixIcon} />,
                      allowClear: true
                    }}
                    captchaProps={{
                      size: "large",
                    }}
                    placeholder={"请输入验证码"}
                    captchaTextRender={(timing, count) => {
                      if (timing) {
                        return `${count} 获取验证码`;
                      }

                      return "获取验证码";
                    }}
                    name="code"
                    rules={[
                      {
                        required: true,
                        message: "请输入验证码！",
                      },
                    ]}
                    onGetCaptcha={async (phone) => {
                      await formRef.current.validateFields(['phone']);//手机号校验
                      const result = await getFakeCaptcha({
                        phone: formRef.current.getFieldValue("phone"),
                      });
                      if (result.code === 0) {
                        return;
                      } else {
                        throw new Error(result.message);
                      }
                    }}
                  />
                  <div style={{ marginBottom: 10 }}>
                    <Checkbox
                      noStyle
                      name="accept"
                      rules={[
                        {
                          required: true,
                        },
                      ]}
                      checked={accept}
                      onChange={(e) => {
                        setaccept(e.target.checked)
                      }}
                    >
                      我已阅读并接受以下条款：
                    </Checkbox>
                  </div>

                  <a onClick={() => {
                    Modal.confirm({
                      title: <h2>PLReport平台服务条款</h2>,
                      content: <Tiaokuan />,
                      okText: "我同意",
                      width: 1200,
                      style: { top: 20 },
                      onOk: () => {
                        setaccept(true)
                      },
                      cancelText: "取消",
                      onCancel: () => {

                      }
                    })
                    setTimeout(() => {
                      let dom = Array.prototype.slice.call(document.getElementsByClassName("ant-modal-wrap"));
                      dom[0].scrollTop = 0;
                    }, 200)
                  }}>《PLReport平台服务条款》</a>
                  <div style={{ marginBottom: 18 }}></div>
                </>
              )
            }

          </LoginForm>
        </div>
        <Modal
          {...modal}
          title="找回密码"
          footer={null}
          onCancel={() => {
            setmodal(s => ({
              ...s,
              visible: false
            }))
          }}
          destroyOnClose={true}
        >
          <ProForm
            formRef={formRefs}
            initialValues={{
              phone: formRef.current?.getFieldValue("phone"),
              code: "",
              password: ""
            }}
            submitter={{
              render: (props, doms) => {
                return [
                  <Button size="large" type="primary" style={{ width: "100%" }} key="submit" onClick={() => props.form?.submit?.()}>
                    提交
                  </Button>,
                ];
              }
            }}
            onFinish={(vals) => {
              postFetch({ url: "/api/user/retrieve_password", params: vals, method: "PUT" }).then(res => {
                if (res.code == 0) {
                  message.success("密码修改成功！请重新登录");
                  setmodal(s => ({
                    ...s,
                    visible: false,
                  }))
                }
              })
            }}

          >
            <ProFormText
              fieldProps={{
                size: "large",
                prefix: <MobileOutlined className={styles.prefixIcon} />,
              }}
              name="phone"
              placeholder={"手机号"}
              rules={[
                {
                  required: true,
                  message: "请输入手机号！",
                },
                {
                  pattern: /^1\d{10}$/,
                  message: "手机号格式错误！",
                },
              ]}
            />
            <ProFormCaptcha
              fieldProps={{
                size: "large",
                prefix: <SafetyCertificateOutlined className={styles.prefixIcon} />,
                allowClear: true
              }}
              captchaProps={{
                size: "large",
              }}
              placeholder={"请输入验证码"}
              captchaTextRender={(timing, count) => {
                if (timing) {
                  return `${count} 获取验证码`;
                }

                return "获取验证码";
              }}
              name="code"
              rules={[
                {
                  required: true,
                  message: "请输入验证码！",
                },
              ]}
              onGetCaptcha={async (phone) => {
                await formRefs.current.validateFields(['phone']);//手机号校验
                const result = await getFakeCaptcha({
                  phone: formRefs.current.getFieldValue("phone"),
                });
                if (result.code === 0) {
                  return;
                } else {
                  throw new Error(result.message);
                }
              }}
            />

            <ProFormText.Password
              name="password"
              fieldProps={{
                size: "large",
                prefix: <LockOutlined className={styles.prefixIcon} />,
              }}
              placeholder={"密码"}
              rules={[
                {
                  required: true,
                  message: ("请输入密码"),
                }
              ]}
            />
          </ProForm>
        </Modal>
      </div>

      <div className={styles.copy}>
        <p>Copyright © 2022 - {moment().format("YYYY")} plreport.com All Rights Reserved. 荀才科技 版权所有</p>
        <p>苏ICP备20000068号-2</p>
      </div>
    </div>
  );
};

export default Login;
